<template>
  <div class="answers-comments">
    <answer-container v-show="answering" @answered="handleAnswered" />
    <div class="answers-list easy-container" v-loading="loading">
      <div ref="answersTop"></div>
      <div v-if="!comments.length" class="easy-container-x2 text-center info">当前没有回答</div>
      <answers-list-item v-for="answer in commentsDisplay" :key="answer.id" :answer="answer" />
    </div>
    <pagination
      :current-page="pagination.current"
      :page-count="pagination.count"
      clear-query
      class="m-t-0"
    />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatComments } from './format';
import AnswersListItem from './answers/answers-list-item';
import AnswerContainer from './answers/answer-container';

export default {
  name: 'AnswersComments', // 回答-评论区
  props: {
    answering: Boolean,
  },
  components: {
    AnswersListItem,
    AnswerContainer,
  },
  data() {
    return {
      loading: false,
      comments: [],
      pagination: {
        current: null,
        count: null,
      },
    };
  },
  computed: {
    ...mapState({ curIssue: 'currentIssue' }),
    // 加载评论列表所需参数
    loadCommentsParams() {
      return {
        placement: 'Issue',
        placementId: this.$route.params.issueId,
        page: this.$route.query.page,
      };
    },
    commentsDisplay() {
      if (this.curIssue.acceptedComment && this.loadCommentsParams.page === 1) {
        const comments = this.comments;
        comments.splice(this.comments.map(i => i.id).indexOf(this.curIssue.acceptedComment.id), 1);
        return [this.curIssue.acceptedComment].concat(comments);
      }
      return this.comments;
    },
  },
  created() { this.loadComments(); },
  methods: {
    // 加载评论列表
    loadComments() {
      this.loading = true;
      this.$api.comments.index(this.loadCommentsParams)
        .then((res) => {
          this.comments = formatComments(res.data);
          this.pagination.current = res.kaminari.current_page;
          this.pagination.count = res.kaminari.total_pages;
          if (this.loadCommentsParams.page) { // 当有page参数（即翻页时），定位到评论区顶部
            this.scrollTopAnswersTop();
          }
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 有新回答
    handleAnswered(answer) {
      this.comments.push(answer);
      this.$emit('update:answering', false);
    },
    // 加载新页码时翻到顶
    scrollTopAnswersTop() {
      this.$refs.answersTop.scrollIntoView({ block: 'center' });
    },
  },
  watch: {
    loadCommentsParams(newVal, oldVal) {
      if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) { // 未知的原因，楼中楼改变参数时，会触发这里
        this.loadComments();
      }
    },
  },
};
</script>

<style></style>
